package com.college.heyuhua.controller;

import com.college.heyuhua.model.FileModel;
import com.college.heyuhua.service.IAdminService;
import com.college.heyuhua.service.IFileService;
import com.college.heyuhua.util.ExcelUtil;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by 赵东坡 on 2019/2/7.
 * Time:15:54
 * 宇宙无敌赵牛逼，祈求永无bug
 */
@Controller
public class ExcelController {

    @Autowired
    private IFileService iFileService;

    @RequestMapping("/exportinfo")
    @ResponseBody
    public void exportinfo(HttpServletRequest request, HttpServletResponse response) {
        List<FileModel> fileList = iFileService.getFileModelList();

        System.out.println(fileList);

        String[] title = {"名称", "简介", "类型", "下载次数"};
        String fileName = "共享资源列表" + System.currentTimeMillis() + ".xls";
        String sheetName = "共享资源列表";
        String content[][] = new String[title.length][4];
        for (int i = 0; i < fileList.size(); i++) {
            FileModel obj = fileList.get(i);
            content[i][0] = obj.getFilename();
            content[i][1] = obj.getFileshort();
            content[i][2] = obj.getFiletype();
            content[i][3] = obj.getDownloadcount() + "";
        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
